﻿using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Silk.NET.Vulkan;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;

namespace VkSample112;

public class ItemMiddleware : IProductionLineMiddleware<VulkanContext>
{
    public void Invoke(VulkanContext context, RenderingProductionLineDelegate<VulkanContext> next)
    {
        var render = context.GetContextRenderObject();
        var pipeline = context.VulkanPipeline;
        int size = Marshal.SizeOf<Matrix4x4>();
        ref MVPMatrix local = ref context.GetMVPMatrix();
        Matrix4x4 mat = local.GetFinalMatrix();
        byte[] data = ArrayPool<byte>.Shared.Rent(size);
        Span<byte> span = data;
        span = span.Slice(0, size);
        mat.ToBytes(ref span, 0);

        var vro = render.GetComponents<VRO>().First();
        var tex = render.GetComponents<VulkanTexture>().First();
        var cmd = context.CommandBuffer;

        cmd.BindDescriptorSets(PipelineBindPoint.Graphics, pipeline.PipelineLayout, 0, null, tex.DescriptorSet);
        cmd.BindVertexBuffers(0, stackalloc ulong[] { 0 }, vro.VerticesBufferInfo.Buffer);
        cmd.PushConstants(pipeline.PipelineLayout, ShaderStageFlags.VertexBit, 0, span.ToArray());
        cmd.Draw(vro.VecticesCount, 1, 0, 0);
        ArrayPool<byte>.Shared.Return(data);
    }
}
